<template>
  <div class="update-avatar">
    <img ref="imgObj" :src="imgData" />
    <div class="toolbar">
      <span @click="$emit('closePop', false)">取消</span>
      <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import { uploadPhoto } from '@/api/user'
// 引入裁剪模块的 css和js函数
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'updateAvatar',
  props: {
    userInfo: {
      required: true
    },
    imgData: {
      required: true
    }
  },

  data () {
    return {
      cropObj: {} // 裁剪对象
    }
  },

  mounted () {
    // 创建裁剪组件对象，并将图片dom传入
    this.cropObj = new Cropper(this.$refs.imgObj, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
    console.log(this.$refs.imgObj)
  },

  methods: {
    onConfirm () {
      this.cropObj.getCroppedCanvas().toBlob(async (blob) => {
        const fd = new FormData()
        fd.append('photo', blob)
        try {
          const res = await uploadPhoto(fd)
          console.log(res)
          this.$toast.success('修改成功')
          this.$emit('closePop', false)

          // eslint-disable-next-line vue/no-mutating-props
          this.userInfo.photo = res.data.data.photo
          console.log(res.data.data.photo)
        } catch (error) {
          console.log(error)
          this.$toast.fail('修改失败')
        }
      })
    }
  },

  created () {}
}
</script>

<style lang="less" scoped>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
